<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="版本号" prop="versionNumber">
        <el-input
          v-model="queryParams.versionNumber"
          placeholder="请输入版本号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新标题" prop="updateTitle">
        <el-input
          v-model="queryParams.updateTitle"
          placeholder="请输入更新标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布时间" prop="publishTime">
        <el-date-picker clearable
          v-model="queryParams.publishTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择发布时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fun:backendUpdateLog:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fun:backendUpdateLog:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fun:backendUpdateLog:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['fun:backendUpdateLog:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 更新记录卡片列表 -->
    <div v-loading="loading" class="update-log-container">
      <div v-for="item in backendUpdateLogList" :key="item.id" class="update-log-card">
        <!-- 卡片头部 -->
         <div class="card-header">
           <div class="version-info">
             <span class="version-text">版本 {{ item.versionNumber }}</span>
             <span class="publish-time">{{ parseTime(item.publishTime, '{y}-{m}-{d}') }}</span>
           </div>
           <div class="card-actions">
             <el-button
               type="text"
               class="collapse-btn"
               @click="toggleCollapse(item.id)"
             >
               <i :class="isCollapsed(item.id) ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"></i>
               {{ isCollapsed(item.id) ? '展开' : '收起' }}
             </el-button>
             <el-checkbox
               :value="ids.includes(item.id)"
               @change="handleCardSelection(item.id, $event)"
               class="card-checkbox"
             ></el-checkbox>
             <el-dropdown trigger="click" @command="handleCommand">
               <el-button type="text" class="more-btn">
                 <i class="el-icon-more"></i>
               </el-button>
               <el-dropdown-menu slot="dropdown">
                 <el-dropdown-item
                   :command="{action: 'edit', row: item}"
                   v-hasPermi="['fun:backendUpdateLog:edit']"
                 >
                   修改
                 </el-dropdown-item>
                 <el-dropdown-item
                   :command="{action: 'delete', row: item}"
                   v-hasPermi="['fun:backendUpdateLog:remove']"
                 >
                   删除
                 </el-dropdown-item>
               </el-dropdown-menu>
             </el-dropdown>
           </div>
         </div>

        <!-- 卡片内容 -->
         <div class="card-content" v-show="!isCollapsed(item.id)">
           <!-- 更新标题 -->
           <h3 class="update-title">{{ item.updateTitle }}</h3>

           <!-- 更新内容描述 -->
           <div v-if="item.updateContent" class="update-description">
             <div class="content-label">更新内容</div>
             <div class="content-text">{{ item.updateContent }}</div>
           </div>

           <!-- 新增功能列表 -->
           <div v-if="item.updateFeatures" class="feature-section">
             <div class="section-title">新增功能</div>
             <div class="feature-list">
               <div
                 v-for="(feature, idx) in parseFeatures(item.updateFeatures)"
                 :key="idx"
                 class="feature-item"
               >
                 <span class="feature-bullet">•</span>
                 <span>{{ feature }}</span>
               </div>
             </div>
           </div>

           <!-- 修复问题列表 -->
           <div v-if="item.bugFixes" class="bugfix-section">
             <div class="section-title">问题修复</div>
             <div class="bugfix-list">
               <div
                 v-for="(bug, idx) in parseFeatures(item.bugFixes)"
                 :key="idx"
                 class="bugfix-item"
               >
                 <span class="bugfix-bullet">•</span>
                 <span>{{ bug }}</span>
               </div>
             </div>
           </div>

           <!-- 备注信息 -->
           <div v-if="item.remark" class="remark-section">
             <div class="section-title">备注</div>
             <div class="remark-text">{{ item.remark }}</div>
           </div>
         </div>

         <!-- 收缩状态下的简要信息 -->
         <div class="card-summary" v-show="isCollapsed(item.id)">
           <h3 class="summary-title">{{ item.updateTitle }}</h3>
           <div class="summary-info">
             <span v-if="item.updateFeatures" class="summary-tag feature-tag">{{ parseFeatures(item.updateFeatures).length }}个新功能</span>
             <span v-if="item.bugFixes" class="summary-tag bugfix-tag">{{ parseFeatures(item.bugFixes).length }}个修复</span>
           </div>
         </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && backendUpdateLogList.length === 0" class="empty-state">
        <i class="el-icon-document-remove"></i>
        <p>暂无更新记录</p>
      </div>
    </div>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改后台更新记录对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="版本号" prop="versionNumber">
          <el-input v-model="form.versionNumber" placeholder="请输入版本号" />
        </el-form-item>
        <el-form-item label="更新类型" prop="updateType">
          <el-select v-model="form.updateType" placeholder="请选择更新类型">
            <el-option label="主版本" value="major"></el-option>
            <el-option label="次版本" value="minor"></el-option>
            <el-option label="补丁版本" value="patch"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="更新标题" prop="updateTitle">
          <el-input v-model="form.updateTitle" placeholder="请输入更新标题" />
        </el-form-item>
        <el-form-item label="更新内容描述">
          <el-input v-model="form.updateContent" type="textarea" :rows="4" placeholder="请输入更新内容描述" />
        </el-form-item>
        <el-form-item label="新增功能列表" prop="updateFeatures">
          <el-input v-model="form.updateFeatures" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="修复问题列表" prop="bugFixes">
          <el-input v-model="form.bugFixes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker clearable
            v-model="form.publishTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发布时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listBackendUpdateLog, getBackendUpdateLog, delBackendUpdateLog, addBackendUpdateLog, updateBackendUpdateLog } from "@/api/fun/backendUpdateLog"

export default {
  name: "BackendUpdateLog",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 后台更新记录表格数据
      backendUpdateLogList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 收缩状态记录
      collapsedCards: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        versionNumber: null,
        updateTitle: null,
        updateContent: null,
        updateFeatures: null,
        bugFixes: null,
        publishTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        versionNumber: [
          { required: true, message: "版本号不能为空", trigger: "blur" }
        ],
        updateType: [
          { required: true, message: "更新类型不能为空", trigger: "change" }
        ],
        updateTitle: [
          { required: true, message: "更新标题不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询后台更新记录列表 */
    getList() {
      this.loading = true
      listBackendUpdateLog(this.queryParams).then(response => {
        this.backendUpdateLogList = response.rows
        this.total = response.total
        this.loading = false

        // 默认收缩所有更新记录
        this.collapsedCards = {}
        this.backendUpdateLogList.forEach(item => {
          this.$set(this.collapsedCards, item.id, true)
        })
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        versionNumber: null,
        updateType: null,
        updateTitle: null,
        updateContent: null,
        updateFeatures: null,
        bugFixes: null,
        publishTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 处理卡片选择
    handleCardSelection(id, checked) {
      if (checked) {
        if (!this.ids.includes(id)) {
          this.ids.push(id)
        }
      } else {
        const index = this.ids.indexOf(id)
        if (index > -1) {
          this.ids.splice(index, 1)
        }
      }
      this.single = this.ids.length !== 1
      this.multiple = this.ids.length === 0
    },
    // 处理下拉菜单命令
    handleCommand(command) {
      if (command.action === 'edit') {
        this.handleUpdate(command.row)
      } else if (command.action === 'delete') {
        this.handleDelete(command.row)
      }
    },
    // 解析功能列表（支持换行符分割）
    parseFeatures(text) {
      if (!text) return []
      return text.split('\n').filter(item => item.trim()).map(item => item.trim())
    },
    // 切换卡片收缩状态
    toggleCollapse(id) {
      this.$set(this.collapsedCards, id, !this.collapsedCards[id])
    },
    // 检查卡片是否收缩
    isCollapsed(id) {
      return !!this.collapsedCards[id]
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加后台更新记录"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getBackendUpdateLog(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改后台更新记录"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBackendUpdateLog(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addBackendUpdateLog(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除后台更新记录编号为"' + ids + '"的数据项？').then(function() {
        return delBackendUpdateLog(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('fun/backendUpdateLog/export', {
        ...this.queryParams
      }, `backendUpdateLog_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>

<style scoped>
.update-log-container {
  padding: 0;
}

.update-log-card {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
  overflow: hidden;
}

.update-log-card:hover {
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px 16px;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f2ff 100%);
  border-bottom: 1px solid #ebeef5;
}

.version-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.version-tag {
  font-weight: 600;
  font-size: 14px;
  padding: 8px 16px;
  border-radius: 20px;
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border: none;
}

.version-tag i {
  margin-right: 6px;
}

.publish-time {
  color: #909399;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.collapse-btn {
  padding: 6px 12px;
  border-radius: 4px;
  color: #606266;
  font-size: 12px;
  transition: all 0.2s;
}

.collapse-btn:hover {
  background: #f5f7fa;
  color: #409eff;
}

.collapse-btn i {
  margin-right: 4px;
}

.card-checkbox {
  margin-right: 8px;
}

.more-btn {
  padding: 8px;
  border-radius: 6px;
  color: #606266;
  transition: all 0.2s;
}

.more-btn:hover {
  background: #f5f7fa;
  color: #409eff;
}

.card-content {
  padding: 28px 32px;
}

.update-title {
  margin: 0 0 24px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.update-description {
  margin-bottom: 24px;
}

.content-label {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 12px;
}

.content-text {
  background: #f8f9fa;
  padding: 12px 16px;
  border-radius: 8px;
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
  border-left: 3px solid #e1e6f0;
  white-space: pre-wrap;
}

.feature-section,
.bugfix-section,
.remark-section {
  margin-bottom: 28px;
}

.feature-section:last-child,
.bugfix-section:last-child,
.remark-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f2f6;
}

.feature-list,
.bugfix-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.feature-item,
.bugfix-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
  padding: 10px 14px;
  background: #fafbfc;
  border-radius: 6px;
  font-size: 14px;
  line-height: 1.5;
  transition: background 0.2s;
}

.feature-item:hover,
.bugfix-item:hover {
  background: #f0f9ff;
}

.feature-bullet,
.bugfix-bullet {
  color: #409eff;
  font-weight: normal;
  font-size: 14px;
  line-height: 1.5;
  flex-shrink: 0;
  width: 14px;
  text-align: center;
}

.bugfix-bullet {
  color: #f56c6c;
}

.feature-item span:last-child,
.bugfix-item span:last-child {
  color: #606266;
  flex: 1;
  line-height: 1.5;
  white-space: pre-wrap;
}

.remark-text {
  background: #fff9e6;
  padding: 16px 20px;
  border-radius: 8px;
  color: #606266;
  line-height: 1.6;
  font-size: 14px;
  border-left: 3px solid #fadb14;
  white-space: pre-wrap;
}

/* 收缩状态样式 */
.card-summary {
  padding: 20px 28px;
  border-top: 1px solid #f0f0f0;
}

.summary-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  line-height: 1.4;
}

.summary-info {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.summary-tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  line-height: 1;
}

.feature-tag {
  background: #e8f4fd;
  color: #409eff;
}

.bugfix-tag {
  background: #fef0f0;
  color: #f56c6c;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #909399;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.empty-state p {
  font-size: 16px;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    padding: 16px 20px 12px;
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .version-info {
    width: 100%;
    justify-content: space-between;
  }

  .card-content {
    padding: 20px;
  }

  .update-title {
    font-size: 16px;
  }
}
</style>
